<template>
  <view class="enterprise-list-view">
    <!--  搜索框  -->
    <fixed-search
      :search-name="curSearchName"
      ipt-placeholder="请输入搜索内容"
      @arrow-click="goHonourPage"
      @handle-search-icon-click="handleSearch"
    />
    <view class="search-total">
      为你查询到<text class="total">{{ searchTotal }}</text
      >条信息
    </view>
    <view class="container">
      <view class="filter-honour">
        <view class="filter-honour-level" @tap="handleHonourLevelFilterClick">
          <view class="text">
            荣誉等级: {{ searchParams.grade || "不限" }}
          </view>
          <view class="icon">
            <u-icon name="arrow-down-fill" />
          </view>
        </view>
        <view class="filter-honour-year" @tap="handleHonourYearFilterClick">
          <view class="text">
            荣誉年份: {{ searchParams.yearList?.[0] || "不限" }}
          </view>
          <view class="icon">
            <u-icon name="arrow-down-fill" />
          </view>
        </view>
        
        <view class="filter-honour-area" @tap="handleHonourAreaFilterClick">
          <view class="text">
            荣誉区域: {{ searchParams.countiesList?.[0] || "不限" }}
          </view>
          <view class="icon">
            <u-icon name="arrow-down-fill" />
          </view>
        </view>
      </view>

      <none-data v-if="enterpriseList.length === 0" />

      <view
        v-else
        class="card-container"
        v-for="item in enterpriseList"
        :key="item.id"
      >
        <text style="color: salmon; font-size: 20rpx">
          <!-- {{ item }} -->
        </text>
        <enterprise-item-card
          :card-detail="item"
          @handle-enterprise-name-click="goEnterpriseDetail"
          @honour-total-click="handleHonourTotalClick"
          @honour-portrayal-click="goPortrayalPage"
          @handleJionClick="handleJionClick"
        />
      </view>
    </view>

    <up-picker
      :show="honourLevelPickerDisabled"
      :columns="honourLevelPickerColumns"
      keyName="filedName"
      title="荣誉等级"
      :closeOnClickOverlay="true"
      :defaultIndex="honourLevelPickerDefaultIndex"
      @confirm="honourLevelPickerConfirm"
      @cancel="honourLevelPickerClosed"
      @close="honourLevelPickerClosed"
    />
    <up-picker
      :show="honourYearPickerDisabled"
      :columns="honourYearPickerColumns"
      title="荣誉年份"
      :closeOnClickOverlay="true"
      :defaultIndex="honourYearPickerDefaultIndex"
      @confirm="honourYearPickerConfirm"
      @cancel="honourYearPickerClosed"
      @close="honourYearPickerClosed"
    />
    <up-picker
      :show="honourAreaPickerDisabled"
      :columns="honourAreaPickerColumns"
      keyName="filedName"
      title="荣誉区域"
      :closeOnClickOverlay="true"
      :defaultIndex="honourAreaPickerDefaultIndex"
      @confirm="honourAreaPickerConfirm"
      @cancel="honourAreaPickerClosed"
      @close="honourAreaPickerClosed"
    />

    <up-popup
      :show="popupShowFlag"
      :safe-area-inset-bottom="false"
      mode="center"
      :round="10"
      @close="popupClose"
      @open="popupOpen"
    >
      <view class="honour-total-popup">
        <view class="title">
          <text class="h3">{{ honourTotal }}</text>
          <text class="h5">项荣誉</text>
        </view>
        <view class="honour-list">
          <view
            class="honour-item"
            v-for="(item, index) in honourTotalDataList"
            :key="index"
          >
            <view class="label">
              {{ item.label }}
            </view>
            <view class="value">
              <text class="h4">
                {{ item.value }}
              </text>
              <text class="h5">项</text>
            </view>
          </view>
        </view>
      </view>
    </up-popup>
    
    <!-- 登录弹窗 -->
    <loginDialog @on-off="userLoginDialog = false" @on-make="headelMake" :indicate="userLoginDialog"> </loginDialog>
  </view>
</template>
<script setup>
import loginDialog from "@/components/login/index.vue";
import fixedSearch from "./components/fixed-search.vue";
import enterpriseItemCard from "./components/enterprise-item-card.vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import { inject, reactive, ref, watch } from "vue";
import {
  getAppEnterpriseListApi,
  getConfigEnterpriseFieldsApi,
  getEnterpriseHonorCountDetailsApi,
  getHonourYearsListApi,
} from "@/api/honour/search";
import { getEnterpriseHonorCountSortMapApi } from "@/api/honour/enterprise-list";
import {
  generateRandomNumId,
  getUrlParamsInH5,
  getUrlParamsInWeixin,
  wxGetSafeTopHeight,
} from "@/utils/utils";
import { customNav } from "@/utils/customNav";
const userLoginDialog = ref(false);
const userLoginInfo = ref("");
/* 顶部搜索栏部分start */
const packageHonourPath = inject("packageHonourPath");
const goHonourPage = () => {
  customNav(`${packageHonourPath}/search-detail`);
};
/* 顶部搜索栏部分end */

/* 企业列表部分start */
let searchParams = ref({
  honorNameList: "",
  grade: null,
  yearList: [],
  countiesList: [],
  page: 1,
  size: 10,
});
const curSearchName = ref("");
const enterpriseList = ref([]);
const curPage = ref(1);
const curPageSize = ref(10);
const totalPages = ref(0);

/**
 * 重置搜索数据的page和pageSize
 */
const resetSearchParamsPageAndSize = () => {
  curPage.value = 1;
  curPageSize.value = 10;
};

const searchTotal = ref(0);
/**
 * 获取企业列表
 * @returns {Promise<void>}
 */
const getAppEnterpriseList = async () => {
  const params = Object.assign(searchParams.value, {
    page: curPage.value,
    size: curPageSize.value,
  });
  const res = await getAppEnterpriseListApi(params);
  const { code, data } = res;
  if (code === 200) {
    const { pages, records, total } = data || {};
    searchTotal.value = total;
    totalPages.value = pages;
    if (records.length === 0) return (status.value = "nomore");
    if (enterpriseList.value.length === 0) {
      enterpriseList.value = records;
    } else {
      enterpriseList.value = enterpriseList.value.concat(records);
    }
  }
};
const status = ref("loadmore");
const isFirstIn = ref(true);
onReachBottom(() => {
  if (curPage.value <= totalPages.value) {
    curPage.value++;
    status.value = "loading";
    getAppEnterpriseList();
  } else {
    status.value = "nomore";
  }
});
/* 企业列表部分end */

/* 列表筛选部分start */

/* 荣耀等级筛选部分start */
const honourLevelPickerDisabled = ref(false);
const honourLevelPickerColumns = reactive([]);
let honourLevelPickerDefaultIndex = reactive([0]);

/**
 * 荣耀等级筛选点击事件
 */
const handleHonourLevelFilterClick = () => {
  const curHonourLevel = searchParams.value.grade || "不限";
  const selectEdIndex = honourLevelPickerColumns[0].findIndex(
    (item) => item.filedName === curHonourLevel
  );
  if (selectEdIndex !== -1) {
    honourLevelPickerDefaultIndex = [selectEdIndex];
  }
  honourLevelPickerDisabled.value = true;
  isFirstIn.value = false;
};
/**
 * 确定按钮点击事件监听
 */
const honourLevelPickerConfirm = (e) => {
  enterpriseList.value = [];
  const selectedVal = e.value[0].filedName;
  const findSelected = honourLevelPickerColumns[0].find(
    (item) => item.filedName === selectedVal
  );
  if (findSelected.filedName === "不限") {
    findSelected.filedName = "";
  }
  searchParams.value.grade = findSelected.filedName;
  honourLevelPickerClosed();
};

/**
 * 取消按钮点击事件和mask层点击事件监听
 */
const honourLevelPickerClosed = () => {
  honourLevelPickerDisabled.value = false;
};
watch(
  () => searchParams.value.grade,
  (newVal, oldVal) => {
    let hasChange;
    if (newVal?.length === 0 && oldVal?.length === 0) {
      hasChange = false;
    } else {
      hasChange = newVal !== oldVal;
    }
    !isFirstIn.value && hasChange && resetSearchParamsPageAndSize();
    !isFirstIn.value && hasChange && getAppEnterpriseList();
  },
  { deep: true, immediate: false }
);

/* 荣耀等级筛选部分end */

/* 荣耀年份筛选部分 start */
const honourYearPickerDisabled = ref(false);
const honourYearPickerColumns = reactive([]);
let honourYearPickerDefaultIndex = reactive([0]);
/**
 * 荣耀年份筛选点击事件
 */
const handleHonourYearFilterClick = () => {
  const curHonourYear = searchParams.value.yearList?.[0] || "不限";
  const selectEdIndex = honourYearPickerColumns[0].findIndex(
    (item) => item === curHonourYear
  );
  if (selectEdIndex !== -1) {
    honourYearPickerDefaultIndex = [selectEdIndex];
  }
  honourYearPickerDisabled.value = true;
  isFirstIn.value = false;
};
/**
 * 取消按钮点击事件和mask层点击事件监听
 */
const honourYearPickerClosed = () => {
  honourYearPickerDisabled.value = false;
};

/**
 * 确定按钮点击事件监听
 */
const honourYearPickerConfirm = (e) => {
  enterpriseList.value = [];
  const selectedVal = e.value[0];
  let findSelected = honourYearPickerColumns[0].find(
    (item) => item === selectedVal
  );
  let yearList = [findSelected];
  if (findSelected === "不限") {
    yearList = [];
  }
  searchParams.value.yearList = yearList;
  honourYearPickerClosed();
};

/**
 * 获取荣耀年份数据列表
 * @returns {Promise<void>}
 */
const getHonourYearsDataList = async () => {
  const res = await getConfigEnterpriseFieldsApi({
    type:"企业荣誉年份"
  });
  const { code, data } = res;
  if (code === 200) {
    const yearList = data[0].children.map((o) =>{
      return o.filedName
    });
    honourYearPickerColumns[0] = yearList;
    honourYearPickerColumns[0].unshift("不限");
  }
};
watch(
  () => searchParams.value.yearList,
  (newVal, oldVal) => {
    let hasChange;
    if (newVal?.length === 0 && oldVal?.length === 0) {
      hasChange = false;
    } else {
      hasChange = newVal !== oldVal;
    }
    !isFirstIn.value && hasChange && resetSearchParamsPageAndSize();
    !isFirstIn.value && hasChange && getAppEnterpriseList();
  },
  { deep: true }
);
/* 荣耀年份筛选部分end */

/* 荣耀地区筛选部分start */
const honourAreaPickerDisabled = ref(false);
const honourAreaPickerColumns = reactive([]);
let honourAreaPickerDefaultIndex = reactive([0]);

/**
 * 荣耀地区筛选点击事件
 */
const handleHonourAreaFilterClick = () => {
  const curHonourArea = searchParams.value.countiesList || "不限";
  const selectEdIndex = honourAreaPickerColumns[0].findIndex(
    (item) => item.filedName === curHonourArea
  );
  if (selectEdIndex !== -1) {
    honourAreaPickerDefaultIndex = [selectEdIndex];
  }
  honourAreaPickerDisabled.value = true;
  isFirstIn.value = false;
};
/**
 * 确定按钮点击事件监听
 */
const honourAreaPickerConfirm = (e) => {
  enterpriseList.value = [];
  const selectedVal = e.value[0].filedName;
  const findSelected = honourAreaPickerColumns[0].find(
    (item) => item.filedName === selectedVal
  );
  searchParams.value.countiesList =
    findSelected.filedName === "不限" ? [] : [findSelected.filedName];
  honourAreaPickerClosed();
};

/**
 * 取消按钮点击事件和mask层点击事件监听
 */
const honourAreaPickerClosed = () => {
  honourAreaPickerDisabled.value = false;
};
watch(
  () => searchParams.value.countiesList,
  (newVal, oldVal) => {
    // console.log('新数据',newVal)
    // console.log('老数据', oldVal)
    let hasChange;
    if (newVal?.length === 0 && oldVal?.length === 0) {
      hasChange = false;
    } else {
      hasChange = newVal !== oldVal;
    }
    !isFirstIn.value && hasChange && resetSearchParamsPageAndSize();
    !isFirstIn.value && hasChange && getAppEnterpriseList();
  },
  { deep: true, immediate: false }
);
/* 荣耀地区筛选部分end */

/**
 * 获取荣耀等级和荣耀区域总数据
 * @returns {Promise<void>}
 */
const getFilterDataList = async () => {
  const res = await getConfigEnterpriseFieldsApi({ type: 0 });
  const { code, data } = res;
  if (code === 200) {
    honourLevelPickerColumns[0] = data.find(
      (item) => item.filedName === "荣誉等级"
    )?.children;
    honourLevelPickerColumns[0].unshift({
      id: generateRandomNumId(19),
      filedName: "不限",
    });
    honourAreaPickerColumns[0] = data.find(
      (item) => item.filedName === "荣誉区域"
    )?.children;
    honourAreaPickerColumns[0].unshift({
      id: generateRandomNumId(19),
      filedName: "不限",
    });
  }
};
/* 列表筛选部分end */

/* 弹出层部分start*/
const popupShowFlag = ref(false);
const popupOpen = () => {};
const popupClose = () => {
  popupShowFlag.value = false;
};
const honourTotalDataList = ref([]);
const honourTotal = ref(0);
const honorMap = ref({});
/**
 * 企业卡片荣誉总数按钮监听
 * @param enterpriseName 企业名称
 */
const handleHonourTotalClick = (enterpriseName) => {
  if (!userLoginInfo.value) {
    userLoginDialog.value = true;
  } else {
    getHonorTotalSortKey(enterpriseName);
  }
};

/**
 * 获取企业荣誉排序map
 * @param enterpriseName
 * @returns {Promise<void>}
 */
const getHonorTotalSortKey = async (enterpriseName) => {
  const res = await getEnterpriseHonorCountSortMapApi();
  const { code, data } = res;
  if (code === 200) {
    const validKeys = data;
    honorMap.value = data
      .filter((key) => validKeys.includes(key))
      .reduce((acc, key) => {
        acc[key] = "";
        return acc;
      }, {});
    await getHonorTotalData(enterpriseName);
  }
};

/**
 * 获取企业荣誉详情
 * @param enterpriseName 企业名称
 * @returns {Promise<void>}
 */
const getHonorTotalData = async (enterpriseName) => {
  const res = await getEnterpriseHonorCountDetailsApi({ enterpriseName });
  const { code, data } = res;
  if (code === 200) {
    honourTotal.value = data["总数"];
    const orderKeys = Object.keys(honorMap.value);
    const orderData = orderKeys.reduce((acc, key) => {
      acc[key] = data[key] || "0";
      return acc;
    }, {});
    honourTotalDataList.value = Object.keys(orderData)
      .map((key) => {
        if (key !== "总数") {
          return { label: key, value: data[key] };
        }
        return null;
      })
      .filter((item) => item !== null);
    popupShowFlag.value = true;
  }
};
/* 弹出层部分end */

/**
 * 搜索框搜索按钮点击事件监听
 * @param searchIptVal 搜索内容
 */
const handleSearch = (searchIptVal) => {
  enterpriseList.value = [];
  searchParams.value.honorNameList = searchIptVal;
  isFirstIn.value = false;
  resetSearchParamsPageAndSize();
  getAppEnterpriseList();
};

/**
 * 跳转企业详情页面
 * @param enterprise 当前点击企业
 */
const goEnterpriseDetail = (enterprise) => {
  if (!userLoginInfo.value) {
    userLoginDialog.value = true;
  } else {
  customNav(
    `enterprise-detail?name=${enterprise.enterpriseName}&&typeName=企业&&id=${enterprise.id}`
  );
  }
};
//跳转加入企业
const handleJionClick = (enterprise) => {};

/**
 * 跳转到荣誉画像页面 当前点击企业
 * @param enterprise
 */
const goPortrayalPage = (enterprise) => {
  if (!userLoginInfo.value) {
    userLoginDialog.value = true;
  } else {
  customNav(
    `enterprise-honor-detail?name=${enterprise.enterpriseName}&&typeName=企业&&id=${enterprise.id}`
  );
  }
  // customNav(
  //   `enterprise-honor-personal?name=${enterprise.enterpriseName}&&typeName=企业&&id=${enterprise.id}`
  // );
};

onLoad(() => {
  /* #ifndef MP-WEIXIN */
  const urlParamsH5 = JSON.parse(getUrlParamsInH5()?.searchParams);
  searchParams.value = Object.assign(searchParams.value, urlParamsH5);
  curSearchName.value = urlParamsH5.honorNameList;
  /* #endif */

  /* #ifdef MP-WEIXIN */
  const urlParamsWX = JSON.parse(getUrlParamsInWeixin()?.searchParams);
  searchParams.value = Object.assign(searchParams.value, urlParamsWX);
  curSearchName.value = urlParamsWX.honorNameList;
  /* #endif */
  userLoginInfo.value = uni.getStorageSync("token");
  getAppEnterpriseList();
  getFilterDataList();
  getHonourYearsDataList();
});
</script>
<style scoped lang=less>
@import url(./style/list.less);
</style>
